package com.xbongbong.help.log;

import com.alibaba.fastjson.JSONObject;
import com.xbongbong.i18n.util.I18nMessageUtil;
import com.xbongbong.paas.constant.PaasConstant;
import com.xbongbong.paas.domain.entity.PaasFormDataEntity;
import com.xbongbong.paas.enums.IndexTypeEnum;
import com.xbongbong.paas.log.MongoLogHelp;
import com.xbongbong.paas.log.constant.LogMemoConstant;
import com.xbongbong.paas.log.thread.LogThreadPoolBeanConfig;
import com.xbongbong.paas.pojo.dto.FormDataAddDTO;
import com.xbongbong.paas.pojo.dto.FormDataUpdateDTO;
import com.xbongbong.paas.toolbox.util.JsonHelperUtil;
import com.xbongbong.paas.toolbox.wrap.UserVO;
import com.xbongbong.pro.formdata.pojo.vo.BeforeSaveVO;
import com.xbongbong.pro.formdata.pojo.vo.BeforeUpdateVO;
import com.xbongbong.pro.formdata.pojo.vo.SaveVO;
import com.xbongbong.pro.formdata.pojo.vo.UpdateVO;
import com.xbongbong.pro.log.pojo.DetailLogPojo;
import com.xbongbong.saas.enums.OperateModuleTypeEnum;
import com.xbongbong.saas.enums.OperateTypeEnum;
import com.xbongbong.saas.enums.RedundantTemplateTypeEnum;
import com.xbongbong.saas.service.toolbox.help.LogHelp;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.List;
import java.util.Objects;

/**
 * @author 吴峰
 * @date 2022/01/05 10:55
 */
@Component
public class InsertDataLogHelp {

    private static final Logger LOG = LoggerFactory.getLogger(InsertDataLogHelp.class);

    @Resource
    private MongoLogHelp mongoLogHelp;
    @Resource
    private LogThreadPoolBeanConfig logThreadPoolBeanConfig;
    @Resource
    private LogHelp logHelp;

    /**
     * 保存日志
     * @param formDataUpdateDTO
     * @param paasFormDataEntity
     * @param logMemo 日志名称
     * @param opObjectName
     * @param operateModuleTypeEnum
     * @param updateVO 插入接口返回的数据，
     * @param beforeUpdateVO 备用参数
     * @return void
     * @author 吴峰
     * @date 2021/2/5 10:47
     */
    public void saveLogger(FormDataUpdateDTO formDataUpdateDTO, PaasFormDataEntity paasFormDataEntity, RedundantTemplateTypeEnum redundantTemplateTypeEnum, String logMemo,
                              String opObjectName, OperateModuleTypeEnum operateModuleTypeEnum, UpdateVO updateVO,
                              BeforeUpdateVO beforeUpdateVO, OperateTypeEnum operateTypeEnum, IndexTypeEnum indexTypeEnum) {
        boolean isCoverage = Objects.equals(1, formDataUpdateDTO.getIsCover());
        if(isCoverage){
            return;
        }
        Runnable runnable = () -> {
            try {
                String corpid = formDataUpdateDTO.getCorpid();
                String userName = updateVO.getUserVO().getName();
                String userId = updateVO.getUserVO().getUserId();
                // 用了处理日志中的子表单数据
                if (Objects.nonNull(paasFormDataEntity.getSubFormData())) {
                    paasFormDataEntity.getData().putAll(paasFormDataEntity.getSubFormData());
                }
                if (Objects.nonNull(beforeUpdateVO.getOldPaasFormData().getSubFormData())) {
                    beforeUpdateVO.getOldPaasFormData().getData().putAll(beforeUpdateVO.getOldPaasFormData().getSubFormData());
                }
                JSONObject newObj = JsonHelperUtil.parseObject(JSONObject.toJSONString(paasFormDataEntity));
                JSONObject oldObj = JsonHelperUtil.parseObject(JSONObject.toJSONString(beforeUpdateVO.getOldPaasFormData()));
                List<DetailLogPojo> detailArr = logHelp.getDetailArr4Data(corpid, redundantTemplateTypeEnum, beforeUpdateVO.getExplainMap(), oldObj, newObj);
                mongoLogHelp.buildLog4DetailArr(detailArr, corpid, userId, userName, operateModuleTypeEnum, operateTypeEnum,
                        formDataUpdateDTO.getDataId().toString(), opObjectName, logMemo, formDataUpdateDTO.getHttpHeader());
            } catch (Exception e) {
                LOG.error("com.xbongbong.paas.service.impl.AbstractFormDataUpdateServiceImpl.afterSaveLog fail", e);
            }
        };
        logThreadPoolBeanConfig.sysLogThreadPool().execute(runnable);
    }

    /**
     * 保存日志
     * @param formDataAddDTO
     * @param paasFormDataEntity
     * @param logName 日志名称
     * @param name
     * @param operateModuleTypeEnum
     * @param saveVO 插入接口返回的数据，
     * @param beforeSaveVO 备用参数
     * @return void
     * @author 吴峰
     * @date 2021/2/5 10:47
     */
    public void saveLogger(FormDataAddDTO formDataAddDTO, PaasFormDataEntity paasFormDataEntity, String logName, String name, OperateModuleTypeEnum operateModuleTypeEnum, SaveVO saveVO,
                              BeforeSaveVO beforeSaveVO) {
        boolean isImport = Objects.equals(1, formDataAddDTO.getIsImport());
        if (isImport) {
            return;
        }
        Runnable runnable = () -> {
            try {
                String corpid = formDataAddDTO.getCorpid();
                Long dataId = saveVO.getDataId();
                // 记录日志(有名称的格式为编号(名称)，无名称的格式为编号)
                OperateTypeEnum operateTypeEnum = OperateTypeEnum.NEW;
                if (Objects.equals(1, formDataAddDTO.getIsBusinessRule())) {
                    // 自定义表单才允许插入
                    operateTypeEnum = OperateTypeEnum.RULE_NEW;
                }
                UserVO userVO = saveVO.getUserVO();
                String userName= userVO.getName();
                String userId = userVO.getUserId();
                if (Objects.equals(userId, PaasConstant.OUT_LINK_USER_ID_PARAM) || Objects.equals(userId, PaasConstant.OUT_LINK_USER_ID)) {
                    // 外链新增的，人员叫外部人员
                    userName = PaasConstant.OUT_LINK_USER_NAME;
                }
                String memo = String.format(I18nMessageUtil.getMessage(LogMemoConstant.LOG_MEMO_USER_ADD_WORK), userName, name, logName);
                mongoLogHelp.buildLog(corpid, userId, userName, operateModuleTypeEnum, operateTypeEnum,
                        dataId.toString(), logName, memo, formDataAddDTO.getHttpHeader());
            } catch (Exception e) {
                LOG.error("com.xbongbong.paas.service.impl.AbstractFormDataServiceImpl.afterSaveLog fail", e);
            }
        };
        logThreadPoolBeanConfig.sysLogThreadPool().execute(runnable);
    }
}
